package com.xebest.web.controller.order;

import com.alibaba.fastjson.JSON;
import com.xebest.common.base.controller.BASEMessage;
import com.xebest.common.base.controller.BaseController;
import com.xebest.common.base.controller.BaseResponse;
import com.xebest.common.enums.erp.order.VenOrderLockEnum;
import com.xebest.constant.XeConstans;
import com.xebest.util.SysSetBeanUtils;
import com.xebest.util.msg.XeVenOrderMsg;
import com.xebest.web.form.XeVenOrderForm;
import com.xebest.web.form.XeVenSplitOrderDetailForm;
import com.xebest.web.form.XeVenSplitOrderForm;
import com.xebest.web.form.XeVenSplitOrdersForm;
import com.xebest.web.service.XeVenSplitOrderService;
import com.xebest.web.view.ErpUserInfo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 拆单类
 * @author ruancz
 */
@RestController
@RequestMapping("split")
public class XeVenSplitOrderController extends BaseController{

	@Autowired
	private XeVenSplitOrderService xeVenSplitOrderService;	//拆单类
	private static final Logger log = LoggerFactory.getLogger(XeVenSplitOrderController.class);


	/**
	 * 拆分订单
	 * @author ruancz
	 */
	@RequestMapping("splitOrder")
	public @ResponseBody BaseResponse splitOrder(@RequestBody XeVenSplitOrdersForm splitOrdersForm){
		log.info("拆分请求参数为：{}",JSON.toJSONString(splitOrdersForm));
		if (StringUtils.isBlank(splitOrdersForm.getOrderId()) || null == splitOrdersForm.getSplitOrderList() || splitOrdersForm.getSplitOrderList().size() <=0) {
			return sendAjaxError(BASEMessage.PARAM_ERROR);
		}
		ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
		try {
			Map<String,Object> map = this.xeVenSplitOrderService.updateSplitOrder(splitOrdersForm,userInfo,getRequestIP());
			return sendAjaxOK();
		} catch (Exception e) {
			log.error("修改订单异常：{}" , e);
			return sendAjaxError();
		} 
	}
	
	/**
	 * 取消拆分
	 * @author ruancz
	 */
	@RequestMapping("unSplitOrder")
	public @ResponseBody BaseResponse unSplitOrder(@RequestBody XeVenOrderForm orderForm){
		log.info("取消拆分订单请求参数为：{}",JSON.toJSONString(orderForm));
		if (null == orderForm || StringUtils.isBlank(orderForm.getOrderId()) || StringUtils.isBlank(orderForm.getOrderStatus().toString())) {
			return sendAjaxError(BASEMessage.PARAM_ERROR);
		}
		//判断订单是否锁单
		if (orderForm.getLockStatus() == VenOrderLockEnum.LOCKED.getValue()) {
			return sendAjaxError(BASEMessage.PARAM_ERROR,XeVenOrderMsg.UNLOCK_MSG);
		}
		ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
		try {
			Map<String, Object> resultMap = this.xeVenSplitOrderService.updateUnSplitOrder(orderForm,userInfo,getRequestIP());
			return sendAjaxOK(resultMap);
		} catch (Exception e) {
			log.error("修改订单异常：{}" , e);
			return sendAjaxError();
		}
	}
	
	/**
	 * 前台拆分订单
	 * @author ruancz
	 */
	@RequestMapping("splitOrderForWeb")
	public @ResponseBody BaseResponse splitOrderForWeb(@RequestBody XeVenSplitOrderForm splitOrderForm){

		log.info("前台拆分订单请求参数为：{}",JSON.toJSONString(splitOrderForm));
		//判断订单是否锁单
		if (splitOrderForm.getLockStatus() == VenOrderLockEnum.LOCKED.getValue()) {
			return sendAjaxError(BASEMessage.PARAM_ERROR, XeVenOrderMsg.UNLOCK_MSG);
		}
		//返回的拆单列表
		List<XeVenSplitOrderForm> orderFormList = new ArrayList<XeVenSplitOrderForm>();
		//原订单信息 用来封装没拆完的订单信息
		XeVenSplitOrderForm splitOrder1 = new XeVenSplitOrderForm();
		//原订单明细信息
		List<XeVenSplitOrderDetailForm> splitOrderDetailList1 = new ArrayList<XeVenSplitOrderDetailForm>();

		//新订单
		XeVenSplitOrderForm splitOrder2 = new XeVenSplitOrderForm();
		//新订单明细
		List<XeVenSplitOrderDetailForm> splitOrderDetailList2  = new ArrayList<XeVenSplitOrderDetailForm>();

//		BigDecimal totalAmount = new BigDecimal("0");//订单金额
		BigDecimal freAmount = (splitOrderForm.getFreAmount() == null ? new BigDecimal("0") : splitOrderForm.getFreAmount());	 //运费金额
		//BigDecimal cpnsPmtAomount = (splitOrderForm.getCpnsPmtAomount() == null ? new BigDecimal("0") : splitOrderForm.getCpnsPmtAomount());	 //商户优惠券总金额
		//BigDecimal platPmtAmount = (splitOrderForm.getPlatPmtAmount() == null ? new BigDecimal("0") : splitOrderForm.getPlatPmtAmount());	 //平台优惠券总金额

		
//		BigDecimal totalAmount = splitOrderForm.getTotalAmount();
		BigDecimal totalAmount = new BigDecimal("0");
//		BigDecimal pmtAmount = (splitOrderForm.getPmtAmount() == null ? new BigDecimal("0") : splitOrderForm.getPmtAmount());  //优惠金额

		BigDecimal totalAmount2 = new BigDecimal("0");   //新订单总价
		BigDecimal specAmount2 = new BigDecimal("0");    //新订单优惠金额
		BigDecimal pmtAmount2 = new BigDecimal("0");    //新订单优惠总金额
        BigDecimal platPmtAmount2 = new BigDecimal("0");    //新订单平台优惠券总金额
        BigDecimal venPmtAmount2 = new BigDecimal("0");    //新订单商户优惠券总金额
        
		BigDecimal totalAmount1 = new BigDecimal("0");  //剩下订单总价
		BigDecimal specAmount1 = new BigDecimal("0");    //剩下订单优惠总金额
		BigDecimal pmtAmount1 =new BigDecimal("0");    //剩下订单优惠总金额
		BigDecimal platPmtAmount1 = new BigDecimal("0");    //剩下订单平台优惠金额
		BigDecimal venPmtAmount1 = new BigDecimal("0");    //剩下订单商户优惠券金额
		for (int i = 0; i < splitOrderForm.getSplitOrderDetailList().size(); i++) {
			//新单明细信息
			XeVenSplitOrderDetailForm splitOrderDetail2 = splitOrderForm.getSplitOrderDetailList().get(i);
			BigDecimal splitNum = splitOrderDetail2.getProSplitNum();
			totalAmount = totalAmount.add(splitOrderDetail2.getProPrice().multiply(splitOrderDetail2.getPurchaseNum()));
			BigDecimal specialDisamount2 = splitOrderDetail2.getSpecialDisamount() == null ? new BigDecimal("0") : splitOrderDetail2.getSpecialDisamount(); //特批优惠金额
			BigDecimal detailPmtAmount2 = splitOrderDetail2.getPmtAmount() == null ? new BigDecimal("0") : splitOrderDetail2.getPmtAmount(); //优惠金额
			BigDecimal detailPlatPmtAmount2 = splitOrderDetail2.getPlatPmtAmount() == null ? new BigDecimal("0") : splitOrderDetail2.getPlatPmtAmount(); //平台优惠券优惠金额
			BigDecimal detailVenPmtAmount2 = splitOrderDetail2.getVenPmtAmount() == null ? new BigDecimal("0") : splitOrderDetail2.getVenPmtAmount(); //商户优惠券优惠金额

			if (splitNum.compareTo(BigDecimal.ZERO) != 0) {

				splitOrder2.setStoreId(splitOrderDetail2.getStoreId());
				splitOrder2.setStoreName(splitOrderDetail2.getStoreName());
				splitOrder2.setOrderId(null);
				splitOrderDetail2.setStoreId(null);
				splitOrderDetail2.setStoreName(null);
				//商品明细    公式 商品明细 特批优惠/优惠=(优惠或特批优惠)*拆分数量/购买数量

				//优惠均摊金额
				BigDecimal proPmtAmount2 = detailPmtAmount2.multiply(splitNum)
						.divide(splitOrderDetail2.getPurchaseNum(),2, RoundingMode.HALF_UP);
				//订单优惠
				pmtAmount2 = pmtAmount2.add(proPmtAmount2);
				//特批优惠金额
				BigDecimal proSpecialDisamount2 = specialDisamount2.multiply(splitNum)
						.divide(splitOrderDetail2.getPurchaseNum(),2, RoundingMode.HALF_UP);
				//订单特批优惠
				specAmount2 = specAmount2.add(proSpecialDisamount2);
				
				//平台优惠券优惠商品优惠分摊金额 李贝贝add v3.1.4
				BigDecimal proPlatPmtAmount2 = detailPlatPmtAmount2.multiply(splitNum)
						.divide(splitOrderDetail2.getPurchaseNum(),2,RoundingMode.HALF_UP);
				//新订单平台优惠券总金额
				platPmtAmount2 = platPmtAmount2.add(proPlatPmtAmount2);
				//商户优惠券优惠商品优惠分摊金额 李贝贝add v3.1.4
				BigDecimal proVenPmtAmount2 = detailVenPmtAmount2.multiply(splitNum)
						.divide(splitOrderDetail2.getPurchaseNum(),2,RoundingMode.HALF_UP);
				//新订单商户优惠券总金额
				venPmtAmount2 = venPmtAmount2.add(proVenPmtAmount2);
				
				//商品总价
				BigDecimal proAmount2 = splitOrderDetail2.getProPrice().multiply(splitNum);
				totalAmount2 = totalAmount2.add(proAmount2);
				splitOrderDetail2.setProTotalPrice(proAmount2);
				splitOrderDetail2.setSpecialDisamount(proSpecialDisamount2);
				splitOrderDetail2.setFreAmount(null);
				splitOrderDetail2.setPmtAmount(proPmtAmount2);
				splitOrderDetail2.setPlatPmtAmount(proPlatPmtAmount2);//设置平台优惠券分摊金额 李贝贝add v3.1.4
				splitOrderDetail2.setVenPmtAmount(proVenPmtAmount2);//设置商户优惠分摊金额
			}
			//不完全分仓订单  剩余订单明细信息
			if(splitNum.compareTo(BigDecimal.ZERO) == 0 || (splitOrderDetail2.getProSplitSurplusNum().compareTo(BigDecimal.ZERO) != 0)){
				if (splitOrderDetail2.getProSplitSurplusNum().compareTo(BigDecimal.ZERO) != 0) {
					XeVenSplitOrderDetailForm splitOrderDetail1 = new XeVenSplitOrderDetailForm();
					splitOrderDetail1 = JSON.parseObject(JSON.toJSONString(splitOrderDetail2),XeVenSplitOrderDetailForm.class);
					splitOrder1.setOrderId(splitOrderForm.getOrderId());
					splitOrderDetail1.setStoreId(null);
					splitOrderDetail1.setStoreName(null);

					BigDecimal splitSurplusNum = splitOrderDetail1.getProSplitSurplusNum();
					//商品总价
					BigDecimal proAmount1 = splitOrderDetail1.getProPrice().multiply(splitSurplusNum);
					//订单总价
					totalAmount1 = totalAmount1.add(proAmount1);

					//订单特批优惠
					BigDecimal proSpecialDisamount1 = specialDisamount2.multiply(splitSurplusNum)
							.divide(splitOrderDetail1.getPurchaseNum(),2, RoundingMode.HALF_UP);
					specAmount1 = specAmount1.add(proSpecialDisamount1);
					//订单优惠
					BigDecimal proPmtAmount1 = detailPmtAmount2
							.multiply(splitSurplusNum)
							.divide(splitOrderDetail1.getPurchaseNum(),2, RoundingMode.HALF_UP);
					pmtAmount1 = pmtAmount1.add(proPmtAmount1);
					
					//平台优惠券优惠商品优惠分摊金额 李贝贝add v3.1.4
					BigDecimal proPlatPmtAmount1 = detailPlatPmtAmount2.multiply(splitSurplusNum)
							.divide(splitOrderDetail1.getPurchaseNum(),2,RoundingMode.HALF_UP);
					//新订单平台优惠券总金额
					platPmtAmount1 = platPmtAmount1.add(proPlatPmtAmount1);
					//商户优惠券优惠商品优惠分摊金额 李贝贝add v3.1.4
					BigDecimal proVenPmtAmount1 = detailVenPmtAmount2.multiply(splitSurplusNum)
							.divide(splitOrderDetail1.getPurchaseNum(),2,RoundingMode.HALF_UP);
					//新订单商户优惠券总金额
					venPmtAmount1 = venPmtAmount1.add(proVenPmtAmount1);
					
					//商品明细 特批优惠金额 运费金额 优惠金额
					splitOrderDetail1.setPurchaseNum(splitSurplusNum);
					splitOrderDetail1.setSpecialDisamount(proSpecialDisamount1);
					splitOrderDetail1.setProTotalPrice(proAmount1);
					splitOrderDetail1.setFreAmount(null);
					splitOrderDetail1.setPmtAmount(proPmtAmount1);
					splitOrderDetail1.setPlatPmtAmount(proPlatPmtAmount1);//设置平台优惠券分摊金额 李贝贝add v3.1.4
					splitOrderDetail1.setVenPmtAmount(proVenPmtAmount1);//设置商户优惠券分摊金额 李贝贝add v3.1.4
					BigDecimal initNull =null;
					splitOrderDetail1.setProSplitNum(initNull);
					splitOrderDetail1.setProSplitSurplusNum(initNull);
					if (splitSurplusNum.compareTo(BigDecimal.ZERO) != 0) {
						BigDecimal normWeight1 = splitOrderDetail2.getNormWeight().divide(splitOrderDetail2.getPurchaseNum(), 2, RoundingMode.HALF_UP)
								.multiply(splitSurplusNum);
						splitOrderDetail1.setNormWeight(normWeight1);
					}
					splitOrderDetailList1.add(splitOrderDetail1);
				}
			}
			if (splitNum.compareTo(BigDecimal.ZERO) != 0) {
				if (splitOrderDetail2.getPurchaseNum().compareTo(BigDecimal.ZERO) != 0) {
					BigDecimal normWeight2 = splitOrderDetail2.getNormWeight().divide(splitOrderDetail2.getPurchaseNum(), 2, RoundingMode.HALF_UP)
							.multiply(splitNum);
					splitOrderDetail2.setNormWeight(normWeight2);
				}
				splitOrderDetail2.setPurchaseNum(splitNum);
				BigDecimal initNull = null;
				splitOrderDetail2.setProSplitNum(initNull);
				splitOrderDetail2.setProSplitSurplusNum(initNull);
				splitOrderDetailList2.add(splitOrderDetail2);
			}
		}
		//拆出订单 设置商品总价 运费总价 优惠总价
		splitOrder2.setGoodsAmount(totalAmount2);
		//splitOrder2.setCpnsPmtAomount(cpnsPmtAomount.multiply(totalAmount2).divide(totalAmount,2, RoundingMode.HALF_UP));
		//splitOrder2.setPlatPmtAmount(platPmtAmount.multiply(totalAmount2).divide(totalAmount,2, RoundingMode.HALF_UP));//设置订单平台优惠券分摊金额 李贝贝add v3.1.4
		splitOrder2.setCpnsPmtAomount(venPmtAmount2);
		splitOrder2.setPlatPmtAmount(platPmtAmount2);
		splitOrder2.setSpecialDisamount(specAmount2);
		splitOrder2.setFreAmount(freAmount.multiply(totalAmount2).divide(totalAmount,2, RoundingMode.HALF_UP));
		splitOrder2.setPmtAmount(pmtAmount2);
		splitOrder2.setPayAmount(totalAmount2.add(splitOrder2.getFreAmount()).subtract(splitOrder2.getPmtAmount()));
		splitOrder2.setTotalAmount(splitOrder2.getPayAmount());
		splitOrder2.setSplitOrderDetailList(splitOrderDetailList2);

		//未拆完订单 设置商品总价 运费总价 优惠总价
		if (null != splitOrderDetailList1 && splitOrderDetailList1.size() > XeConstans._XE_ZERO) {
			splitOrder1.setStoreId(splitOrderForm.getStoreId());
			splitOrder1.setStoreName(splitOrderForm.getStoreName());
			splitOrder1.setGoodsAmount(totalAmount1);
			splitOrder1.setSpecialDisamount(specAmount1);
			//splitOrder1.setCpnsPmtAomount(venPmtAmount1.multiply(totalAmount1).divide(totalAmount, 2, RoundingMode.HALF_UP));
			//splitOrder1.setPlatPmtAmount(platPmtAmount1.multiply(totalAmount1).divide(totalAmount,2, RoundingMode.HALF_UP));//设置订单平台优惠券分摊金额 李贝贝add v3.1.4
			splitOrder1.setCpnsPmtAomount(venPmtAmount1);
			splitOrder1.setPlatPmtAmount(platPmtAmount1);
			splitOrder1.setFreAmount(freAmount.multiply(totalAmount1).divide(totalAmount, 2, RoundingMode.HALF_UP));
			splitOrder1.setPmtAmount(pmtAmount1);
			splitOrder1.setPayAmount(totalAmount1.add(splitOrder1.getFreAmount()).subtract(splitOrder1.getPmtAmount()));
			splitOrder1.setTotalAmount(splitOrder1.getPayAmount());
			splitOrder1.setSplitOrderDetailList(splitOrderDetailList1);
			if (null != splitOrderDetailList2 && splitOrderDetailList2.size() > XeConstans._XE_ZERO) {
				orderFormList.add(splitOrder2);
			}
			orderFormList.add(splitOrder1);
		} else {
			orderFormList.add(splitOrder2);
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("orderFormList",orderFormList);
		return sendAjaxOK(resultMap);
	}
}
